package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/live-broadcasts/api/request"
	"zg3/live-broadcasts/internal/dao"
	"zg3/live-broadcasts/internal/model"
	"zg3/live-broadcasts/pkg"
)

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.ConditionQuery(&model.User{Account: req.Account}, &user)
	if user.Id == 0 {
		users := model.User{
			Account:  req.Account,
			Password: req.Password,
		}
		dao.Create(&users)
		token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{ID: users.Id})
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册登录成功",
			"data": token,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
			"data": false,
		})
		return
	}
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{ID: user.Id})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func EnterLive(c *gin.Context) {
	var req request.EnterLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var liveUser model.LiveUser
	dao.ConditionQuery(&model.LiveUser{
		LiveId: req.LiveId,
		UserId: c.GetUint("userId"),
	}, &liveUser)

	if liveUser.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "已经进入直播间",
			"data": false,
		})
		return
	}
	liveUsers := model.LiveUser{
		LiveId: req.LiveId,
		UserId: c.GetUint("userId"),
	}
	dao.Create(&liveUsers)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "进入直播间成功",
		"data": liveUsers,
	})
	return
}
